import VueRouter from "vue-router";
import Vue from "vue";
import routes from "@/routes/routes";
import store from "@/store";

Vue.use(VueRouter)

//重写push
const oldPush = VueRouter.prototype.push

VueRouter.prototype.push = function (
    location,
    onComplete = ()=>{},
    onAbort = ()=>{},
    ){
    oldPush.call(this,location,onComplete,onAbort)
}

//重写replace
const oldReplace = VueRouter.prototype.replace

VueRouter.prototype.replace = function (
    location,
    onComplete = ()=>{},
    onAbort = ()=>{},
){
    oldReplace.call(this,location,onComplete,onAbort)
}

const router = new VueRouter({
    mode:"history",
    routes
})

const whitePath = ["login","home","search","detail","shopCart","addCartSuccess","register"]
router.beforeEach(async (to,from,next)=>{
    const token = store.state.user.token
    if(token){
        if(to.name === "login"){
            next("/home")
        }else {
            const isUserInfo = !!store.state.user.userInfo.nickName
            if(isUserInfo){
                next()
            }else {
                try {
                    await store.dispatch("user/getUserInfo")
                    next()
                }catch (e){
                    await store.dispatch("user/getRemove")
                    next(`/login?redirect=${to.name}`)
                }
            }
        }
    }else {
        if(whitePath.includes(to.name)){
            next()
        }else {
            next(`/login?redirect=${to.name}`)
        }
    }
})

export default router